<template>
    <div>
        <a-modal
         v-model:visible="visible" 
         :title="formState.id?(formState.view?'查看':'编辑检验信息'):'新增检验信息'"  
         @ok="handleOk" 
         @cancel="visible = false"
         class="inspectAddEdit-add-edit-modal"
         width="100%"
         wrapClassName="full-modal"
         :footer="null"
        >
            <div v-if="visible">
                <div class="process-handling-card">
                    <a-tabs type="card" v-model:activeKey="activeKey" >
                        <a-tab-pane key="检验信息" tab="检验信息"></a-tab-pane>
                        <a-tab-pane key="检验项目" tab="检验项目"></a-tab-pane>
                    </a-tabs>
                </div>
                <div v-show="activeKey == '检验信息'" style="height: calc(100vh - 152px);overflow-y: auto;">

                    <!-- fbgbh 报告编号、fyxq 有效期、fsjbm 送检部门、fsjrq 送检日期、fbgrq 报告日期、fjymd 检验目的、fjyyj 检验依据、fjyjl 检验结论、fbgsbz 报告书备注 -->
                    <a-form :form="form" layout="horizontal" class="add-edit-form">
                        <a-form-item label="报告编号">
                            <a-input
                            v-model:value="formState.fbgbh"
                            placeholder="请输入报告编号"
                            v-decorator="[
                                'fbgbh', { initialValue:formState.fbgbh, rules: rules.fbgbh}
                            ]"/>
                        </a-form-item>
                        <a-form-item label="有效期">
                            <a-date-picker
                                v-model:value="formState.fyxq"
                                placeholder="请选择有效期"
                                v-decorator="[
                                    'fyxq', { initialValue:formState.fyxq, rules: rules.fyxq}
                                ]"
                            />
                        </a-form-item>
                        <a-form-item label="送检部门">
                            <a-input
                            v-model:value="formState.fsjbm"
                            placeholder="请输入送检部门"
                            v-decorator="[
                                'fsjbm', { initialValue:formState.fsjbm, rules: rules.fsjbm}
                            ]"/>
                        </a-form-item>
                        <a-form-item label="送检日期">
                            <a-date-picker
                                v-model:value="formState.fsjrq"
                                placeholder="请选择送检日期"
                                v-decorator="[
                                    'fsjrq', { initialValue:formState.fsjrq, rules: rules.fsjrq}
                                ]"
                            />
                        </a-form-item>
                        <a-form-item label="报告日期">
                            <a-date-picker
                                v-model:value="formState.fbgrq"
                                placeholder="请选择报告日期"
                                v-decorator="[
                                    'fbgrq', { initialValue:formState.fbgrq, rules: rules.fbgrq}
                                ]"
                            />
                        </a-form-item>
                        <a-form-item label="检验目的" class="flex-1-box">
                            <a-textarea 
                                placeholder="请输入检验目的"
                                v-model:value="formState.fjymd"
                                :autosize="{ minRows: 2, maxRows: 10000 }"
                                v-decorator="[
                                'fjymd', { initialValue:formState.fjymd, rules: rules.fjymd}
                                ]"
                            ></a-textarea>
                        </a-form-item>
                        <a-form-item label="检验依据" class="flex-1-box">
                            <a-textarea 
                                placeholder="请输入检验依据"
                                v-model:value="formState.fjyyj"
                                :autosize="{ minRows: 2, maxRows: 10000 }"
                                v-decorator="[
                                'fjyyj', { initialValue:formState.fjyyj, rules: rules.fjyyj}
                                ]"
                            ></a-textarea>
                        </a-form-item>
                        <a-form-item label="检验结论" class="flex-1-box">
                            <a-textarea 
                                placeholder="请输入检验结论"
                                v-model:value="formState.fjyjl"
                                :autosize="{ minRows: 2, maxRows: 10000 }"
                                v-decorator="[
                                'fjyjl', { initialValue:formState.fjyjl, rules: rules.fjyjl}
                                ]"
                            ></a-textarea>
                        </a-form-item>
                        <a-form-item label="报告书备注" class="flex-1-box">
                            <a-textarea 
                                placeholder="请输入报告书备注"
                                v-model:value="formState.fbgsbz"
                                :autosize="{ minRows: 2, maxRows: 10000 }"
                                v-decorator="[
                                'fbgsbz', { initialValue:formState.fbgsbz, rules: rules.fbgsbz}
                                ]"
                            ></a-textarea>
                        </a-form-item>
                        <a-form-item label="相关附件" class="flex-1-box">
                            <div v-if="!formState.view">
                                <a-upload :disabled="uploadLoading"
                                v-if="formState.id"
                                :beforeUpload="enterpriseBeforeUpload" 
                                :showUploadList="false"
                                action="" 
                                @change="RelatedAccessoriesUploadSave">
                                    <a-button :loading="uploadLoading" style="margin-right: 15px;" class="blue-btn" type="primary" >上传</a-button>
                                </a-upload>
                                <a-button v-else style="margin-right: 15px;" class="blue-btn" type="primary" @click="onlyUploadSave">上传</a-button>
                            </div>
                                <div class="related-accesso-box">
                                <div v-for="(item,index) in fjxxList" :key="index">
                                    <span style="font-weight: 600;">{{ item.fwjxsmc+item.fwjlx }}</span>
                                    <a-icon style="color: #ff8000;padding: 5px;font-size: 16px;" type="delete" @click="deleteClick(item)" v-if="!formState.view"/>
                                    <a-icon style="color: rgb(24, 144, 255);padding: 5px;font-size: 16px;" type="eye" @click="viewClick(item)" v-if="item.fwjlx == '.pdf'"/>
                                    <a-icon style="color: rgb(24, 144, 255);padding: 5px;font-size: 16px;" type="download" @click="downloadClick(item)"/>
                                </div>
                            </div>
                        </a-form-item>
                        <!-- <div style="width: 100%;">
                            <table border="1" class="material-table">
                                <tr>
                                    <th style="text-align: center;padding: 5px;">文件目录</th>
                                    <th style="text-align: center;padding: 5px;">文件清单</th>
                                    <th style="text-align: center;padding: 5px;">操作 <span style="color: red;font-size: 12px;">（提示：批量上传文件放在同一个文件夹内，选择文件夹上传）</span></th>
                                </tr>
                                <tr v-for="(item,index) in fjxxList" :key="index">
                                    <td style="width: 30%;text-align: center;">{{ item.wjml }}</td>
                                    <td style="width: 50%;">
                                        <div style="display: flex;width: 100%;flex-wrap: wrap;">
                                            <div class="file-td-box" v-for="(term,tIndex) in item.wjList">
                                                <a-icon class="delete-icon-v" type="delete" @click="deleteClick(term)" v-if="!formState.view"/>
                                                <a-icon class="eye-icon-v" type="eye" @click="viewClick(term)" v-if="term.fwjlx == '.pdf'"/>
                                                <a-icon class="download-icon-v" type="download" @click="downloadClick(term)"/>
                                                <a-icon class="file-icon-v" type="file-pdf" />
                                                <span>{{ term.fwjxsmc+term.fwjlx }}</span>
                                            </div>
                                        </div>
                                    </td>
                                    <td style="width: 20%;">
                                        <div style="display: flex;justify-content: center;padding: 5px;" v-if="!formState.view">
                                            <a-upload :disabled="uploadLoading"
                                            v-if="formState.fyzmc"
                                            style="display: inline-block;" 
                                            :beforeUpload="enterpriseBeforeUpload" 
                                            action="" 
                                            @change="enterpriseUpload($event,item)">
                                                <a-button :loading="uploadLoading" style="margin-right: 15px;" class="blue-btn" type="primary" @click="uploadSave">上传</a-button>
                                            </a-upload>
                                            <a-button v-else style="margin-right: 15px;" class="blue-btn" type="primary" @click="handleOk(true)">上传</a-button>
                                            <a-upload :disabled="uploadLoading"
                                            v-if="formState.fyzmc"
                                            style="display: inline-block;" 
                                            :beforeUpload="enterpriseBeforeUpload" 
                                            action="" 
                                            @change="enterpriseUpload($event,item)" directory>
                                                <a-button :loading="uploadLoading" class="blue-btn" type="primary" @click="uploadSave">批量上传</a-button>
                                            </a-upload>
                                            <a-button v-else class="blue-btn" type="primary" @click="handleOk(true)">批量上传</a-button>
                                        </div>
                                        
                                    </td>
                                </tr>
                            </table>
                        </div> -->
                    </a-form>
                    <div style="
                        display: flex; justify-content: flex-end;
                        margin-top: 20px; width: 100%;
                        position: absolute; left: 0;
                        bottom: 0; padding: 18px 24px;
                        background-color: #fff;">
                        <a-button @click="visible = false">取消</a-button>
                        <a-button v-if="!formState.view" style="margin: 0 20px;" class="blue-btn" type="primary" @click="handleOk(true)">保存</a-button>
                        <a-button v-if="!formState.view" class="blue-btn" type="primary" @click="handleOk(false)">保存并关闭</a-button>
                    </div>
                </div>
                <div v-show="activeKey == '检验项目'" style="height: calc(100vh - 142px);overflow-y: auto;">
                    <commpVxeTable
                        :key="inspectionItemsRefreshTable"
                        ref="headmanVxeTable"
                        :config="{
                            api:assessCheckApi.spcyQyInfoqueryQyJyxmList,
                            rowId: 'id',
                            paramet:{
                                fjyid:formState.id,
                            },
                            autoHidden:true,
                        }" 
                        :isCanWrap="true"
                        :columns="inspectionItemsColumnsVxe" 
                        :formItem="[]"
                        :occupancyHeight="120"
                        
                    >  
                        <template v-slot:externalOperations="{data}" v-if="!formState.view">
                            <vxe-form-item>
                                <template>
                                    <a-button class="blue-btn" type="primary" @click="inspectionItemsAddClick(1)">新增</a-button>
                                </template>
                            </vxe-form-item>
                        </template>
                        <template v-slot:operation_btn="{row}" data-desc="自定操作栏">
                            <a-form layout="inline" class="search-form" >
                                <a-form-item v-if="!formState.view">
                                    <a-button class="blue-btn" type="primary" @click="inspectionItemsEditClick(row,0)" >编辑</a-button>
                                </a-form-item>
                                <a-form-item v-if="!formState.view">
                                    <a-button class="red-btn" type="primary" @click="inspectionItemsDeleteClick(row,0)" >删除</a-button>
                                </a-form-item>
                            </a-form> 
                        </template>
                    </commpVxeTable>
                </div>
            </div>
            <serverEditingView ref="serverEditingViewRef" @refreshChange="$event=>{}"/>
            <inspectionItems ref="inspectionItemsRef" @inspectionItemsSuccess="inspectionItemsSuccess" />
        </a-modal>
    </div>
</template>
<script>
import compSelector from '@/components/compSelector/compSelector.vue'
import serverEditingView from '@/components/comp-model-series/server-editing-view'
import moment from 'moment'
import YchConstant from "@/api/YchConstant";
import blobType from '@/common/blobType'
import assessCheckApi from '../service/api'
import { 
    spcyQyInfoQueryGyyzWjml, 
    spcyQyInfoUploadMoreTypeFile, 
    getFileTypeServe, 
    deleteFileById, 
    getCrossLocalFile, 
    spcyQyInfouploadQyJyxxFile,
    spcyQyInfoqueryQyJyxxFileList,
    spcyQyInfodeleteJyxm,
} from '../service/index'
import inspectionItems from './inspectionItems.vue'
import commpVxeTable from '@/components/commp-vxe-table/commp-vxe-table.vue'
export default {
    components:{
        serverEditingView,
        compSelector,
        inspectionItems,
        commpVxeTable,
    },
    props:{

    },
    data(){
        return{
            assessCheckApi:assessCheckApi,
            activeKey:'检验信息',
            visible:false,
            formState:{},
            form: this.$form.createForm(this, { name: 'coordinated' }),
            rules:{
                fbgbh: [{
                    required: true,
                    message: '请输入报告编号',
                    trigger: 'blur',
                }],
                fyxq: [{
                    type:'object',
                    required: true,
                    message: '请选择有效期',
                    trigger: 'blur',
                }],
                fsjbm: [{
                    required: true,
                    message: '请输入送检部门',
                    trigger: 'blur',
                }],
                fsjrq: [{
                    type:'object',
                    required: true,
                    message: '请选择送检日期',
                    trigger: 'blur',
                }],
                fbgrq: [{
                    type:'object',
                    required: true,
                    message: '请选择报告日期',
                    trigger: 'blur',
                }],
                fjymd: [{
                    required: true,
                    message: '请输入检验目的',
                    trigger: 'blur',
                }],
                fjyyj: [{
                    required: true,
                    message: '请输入检验依据',
                    trigger: 'blur',
                }],
                fjyjl: [{
                    required: true,
                    message: '请输入检验结论',
                    trigger: 'blur',
                }],
                fbgsbz: [{
                    required: true,
                    message: '请输入报告书备注',
                    trigger: 'blur',
                }],
            },
            fjxxList:[],
            uploadLoading:false,
            inspectionItemsRefreshTable:null,
            inspectionItemsColumnsVxe:[{
                title: '序号', //列头显示文字
                field: 'fxmxh',
            },{
                title: '项目名称', //列头显示文字
                field: 'fxmmc',
            },{
                title: '标准规定', //列头显示文字
                field: 'fbzgd',
            },{
                title: '检验数据', //列头显示文字
                field: 'fjysj',
            },{
                title: '项目检验结论', //列头显示文字
                field: 'fxmjyjl',
            },{
                    title: '操作',
                    field: 'id',
                    slots: {
                        // 使用插槽模板渲染
                        default: 'operation_btn',
                    },
                    width:180,
                    fixed:'right'
            }],
            
        }
    },
    watch:{

    },
    mounted(){
    },
    methods:{
        getData(val){
            this.formState = {}
            this.formState = val
            this.formState.fyxq = val.fyxq?moment(val.fyxq):''
            this.formState.fsjrq = val.fsjrq?moment(val.fsjrq):''
            this.formState.fbgrq = val.fbgrq?moment(val.fbgrq):''
            this.getFile(val)
            this.inspectionItemsRefreshTable = Date.now()
        },
        forderChange(val){
            //console.log(val)
            if(!val){
                this.formState.forder = 1
            }
        },
        getFile(val){
            spcyQyInfoqueryQyJyxxFileList({id:val.id?val.id:''}).then(res=>{
                if(res.code == 200){
                    this.fjxxList = res.result
                }else{
                    this.$message.warning(res.message)
                }
            })
        },
        deleteClick(val){
            var that = this
            this.$confirm({
                title:'您确认要删除吗？',
                // icon: createVNode(ExclamationCircleOutlined),
                onOk() {
                    deleteFileById({id:val.id}).then(res=>{
                        if(res.code == 200){
                            that.$message.success('删除成功')
                            that.getFile(that.formState)
                        }else{
                            that.$message.warning(res.message)
                        }
                    })
                },
                
            });
        },
        viewClick(val){
            this.$refs.serverEditingViewRef.getData({id:val.id,fwjlx:val.fwjlx,type:'企业信息'})
            this.$refs.serverEditingViewRef.serverEditingVisible = true
        },
        lookOverClick(val){
            getFileTypeServe({id:val.id}).then(res=>{
                if(res.code == 200){
                    if(res.result == '.pdf'){
                        window.open(
                            bootConfig[process.env.NODE_ENV].locality_ApI+YchConstant.SPZX_SPCY+'/spcySqsxWjjl/getCrossLocalFile?id='+val.id
                        )
                    }else{
                        this.$message.warning('只能查看pdf文件')
                    }
                    
                }
                
            })
        },
        downloadClick(val){
            
            var that = this
            var fileName = val.fwjxsmc
            let param = {id:val.id}
            getFileTypeServe({id:val.id}).then(res=>{
                if(res.code == 200){
                    getCrossLocalFile(param).then((data) => {
                        if (!data) {
                            that.$message.warning('文件下载失败')
                            return
                        }else{
                        // if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        //     window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }))
                        // } else {
                            let url = window.URL.createObjectURL(new Blob([data], { type: blobType.type[blobType.suffix.indexOf(val.fwjlx)] }))
                            let link = document.createElement('a')
                            link.style.display = 'none'
                            link.href = url
                            link.setAttribute('download', fileName + res.result)
                            document.body.appendChild(link)
                            link.click()
                            document.body.removeChild(link) //下载完成移除元素
                            window.URL.revokeObjectURL(url) //释放掉blob对象
                        // }
                        }
                    })
                }
                
            })
        },
        enterpriseBeforeUpload(e){
            return false
        },
        uploadSave(){
            if(!this.formState.id){
                this.handleOk(true,true)
            }
        },
        enterpriseUpload({file},val){//
            var that = this
            this.uploadLoading = true
            if(typeof file.uid !== 'undefined') {
                // if(file.name.indexOf(".xls") !== -1 || file.name.indexOf(".xlsx") !==-1) {
                    const fileData = new FormData();
                    fileData.append("file",file);
                    fileData.append("id",this.formState.id);
                    fileData.append("fwjlx1",val.wjml);
                    
                    spcyQyInfoUploadMoreTypeFile(fileData).then(res => {
                        if(res.code){
                            if(res.code == 200){
                                this.uploadLoading = false
                                that.$message.success(res.message)
                            }else{
                                this.uploadLoading = false
                                that.$message.warning(res.message)
                            }
                            
                        }
                        if(res.byteLength){
                            if(res.code && res.code !== 200){
                                this.uploadLoading = false
                                that.$message.warning('请上传对应文件类型或者联系管理员!')
                            }else{
                                this.uploadLoading = false
                                that.$message.success('上传成功')
                            }
                        }
                        this.getFile(this.formState)
                    })
                // }
                
            }
        },
        onlyUploadSave(){
            if(!this.formState.id){
                this.$message.warning('请先保存检验信息')
            }
            
        },
        //上传相关文件
        RelatedAccessoriesUploadSave({file}){
            
            this.uploadLoading = true
            // if(file.name.indexOf(".xls") !== -1 || file.name.indexOf(".xlsx") !==-1) {
            const fileData = new FormData();
            fileData.append("file",file);
            fileData.append("id",this.formState.id);
            // fileData.append("fwjlx1",val.wjml);
            
            spcyQyInfouploadQyJyxxFile(fileData).then(res => {
                if(res.code){
                    if(res.code == 200){
                        this.uploadLoading = false
                        this.$message.success(res.message)
                    }else{
                        this.uploadLoading = false
                        this.$message.warning(res.message)
                    }
                    
                }
                this.getFile(this.formState)
            })
            // }
        },
        //审评项目
        inspectionItemsAddClick(){
            if(this.formState.id){
                this.$refs.inspectionItemsRef.getData({fjyid:this.formState.id})
                this.$refs.inspectionItemsRef.visible = true
            }else{
                this.activeKey == '检验信息'
                this.$message.warning('请先保存检验信息')
            }
        },
        inspectionItemsEditClick(row){
            this.$refs.inspectionItemsRef.getData({fjyid:this.formState.id,...row})
            this.$refs.inspectionItemsRef.visible = true
        },
        inspectionItemsDeleteClick(val){
            var that = this
            this.$confirm({
                title:'您确认要删除吗？',
                // icon: createVNode(ExclamationCircleOutlined),
                onOk() {
                    spcyQyInfodeleteJyxm({id:val.id}).then(res=>{
                        if(res.code == 200){
                            that.$message.success('删除成功')
                            that.inspectionItemsRefreshTable = Date.now()
                        }else{
                            that.$message.warning(res.message)
                        }
                    })
                },
                
            });
        },
        
        inspectionItemsSuccess(){
            this.inspectionItemsRefreshTable = Date.now()
        },
        handleOk(val){
            this.form.validateFields((err, values) => {
                if (!err) {
                    if(this.formState.id){
                        this.$emit('currenteditItem',{
                            ...this.formState,
                            ...values,
                            fyxq:this.formState.fyxq?moment(this.formState.fyxq).format('YYYY-MM-DD'):'',
                            fsjrq:this.formState.fsjrq?moment(this.formState.fsjrq).format('YYYY-MM-DD'):'',
                            fbgrq:this.formState.fbgrq?moment(this.formState.fbgrq).format('YYYY-MM-DD'):'',
                        },val)
                    }else{
                        this.$emit('currentaddItem',{
                            ...this.formState,
                            ...values,
                            fyxq:this.formState.fyxq?moment(this.formState.fyxq).format('YYYY-MM-DD'):'',
                            fsjrq:this.formState.fsjrq?moment(this.formState.fsjrq).format('YYYY-MM-DD'):'',
                            fbgrq:this.formState.fbgrq?moment(this.formState.fbgrq).format('YYYY-MM-DD'):'',
                        },val)
                    }
                    
                }
            })
        },
    }
}
</script>
<style lang="less">
.inspectAddEdit-add-edit-modal{
    .add-edit-form{
        display: flex;
        flex-wrap: wrap;
        .ant-form-item{
            display: flex;
            margin-bottom: 10px;
        }
        .ant-form-item-label{
            width: 100px;
        }
        .ant-form-item-control-wrapper{
            width: 180px;
        }
        .flex-1-box{
            width: 100%;
            .ant-form-item-control-wrapper{
                flex: 1;
            }
        }
    }
    .material-table{
        width: 100%;
        border-color: #d9d9d9 !important;
    }
    .material-warning-tabs{
        .ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab{
            padding-right: 30px;
            margin-right: 10px !important;
        }
        .ant-tabs-tab{
            border-radius: 10px 10px 0 0 !important;
        }
        .ant-tabs-nav-container{
            padding-left: 10px;
            height: 50px !important;
        }
        .ant-tabs-nav-scroll{
            padding-top: 10px;
        }
        .ant-tabs-tab-active{
            background-color: #5ca3e5 !important;
            color: #fff !important;
            border-color: #5ca3e5 !important;
            box-shadow: 0px 0px 12px 0px #5ca3e5;
        }
    }
}
.file-td-box{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-content: space-between;
    width: 104px;
    height: 104px;
    overflow: hidden;
    border-radius: 2px;
    border: 1px solid #d9d9d9;
    padding: 8px;
    margin: 8px;
    position: relative;
    .delete-icon-v{
        font-size: 16px;
        position: absolute;
        color: rgb(24, 144, 255);
        right: 11px;
        top: 3px;
    }
    .eye-icon-v{
        font-size: 16px;
        position: absolute;
        color: rgb(24, 144, 255);
        right: 11px;
        top: 38px;
    }
    .download-icon-v{
        width: 20px;
        font-size: 16px;
        position: absolute;
        color: rgb(24, 144, 255);
        right: 9px;
        top: 20px;
    }
    .download-icon-apply{
        top: 10px;
    }
    .fjbz-text-v{
        color: #ff8000;
        font-size: 12px !important;
        display: inline-block;
        width: 28px;
        position: absolute;
        top: 5px;
        left: 3px;
    }
    .file-icon-v{
        font-size: 42px;
        color: rgb(24, 144, 255);
    }
    .file-icon-v{
        font-size: 42px;
        color: rgb(24, 144, 255);
    }
    span{
        height: 40px;
        display:block;
        text-overflow: -o-ellipsis-lastline;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        font-size: 14px;
    }
}
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
    height: calc(100vh - 103px);
    padding: 10px;
    overflow: auto;
  }
}
.ant-upload-list{
    display: none;
}
.ant-upload-list-item{
    display: none !important;
}
</style>